package com.myfojing.foshuoliaozhibingjing;

import android.Manifest;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import com.google.android.material.snackbar.Snackbar;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.lang.ref.WeakReference;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.Locale;
import java.util.Objects;
import java.util.Queue;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.myfojing.foshuoliaozhibingjing.R.string.zhuyin_huixinag;


enum Status {STOPPED, PLAYING, PAUSED}

enum Action {PLAY, PAUSE, RESUME, STOP}

enum Type {LIAOZHI, ZHOUCHI, YAOSHIFO, XINJING}

enum Kind {JINGWEN, ZHOUYU, HUIXIANG}

public class MainActivity extends AppCompatActivity {

    final static int M_PROGRESS = 2;  // 消息：进度
    final static int M_NEXTCLAUSE = 3;  // 消息：下一句
//    final static int M_TIMEOUT = 4;  // 超时
//    final static int M_TIMEOUT_STOP = 5; // 超时关闭

    final static int T_JINGWEN = 0;  // 类型
    final static int TOTAL_HUIXIANG = 1;
    final int CODE_SETTING = 10;
    // 朗读次数
    // 常数
    int TOTAL_JINGWEN = 1;
    int TOTAL_ZHOU = 3;
    Status status;

    Type type = Type.LIAOZHI;
    Sutra sutra_c;

    // 数据
    SharedPreferences sharedPreferences = null;

    // 朗读
    boolean no_speech;
    boolean wifi_is_only;
    boolean network_is_ready;
    boolean blRepeat;

    Queue<Sutra> queue;  // 依次放入：经文，咒语，回向
    String[] sentence = new String[2];

    XunfeiTTS mTts_xunfei;  // 讯飞TTS
    int count_jingwen;
    int count_zhouyu;
    int count_huixiang;

    // .进度
    //int clause_length;  // 分句长度
    Drawable drawable_play;
    //Drawable drawable_play_off;
    // .发言人
    boolean speaker_is_male;
    // UI element
    Button btnPlay;
    Button btnPause;
    Button btnStop;
    WebView webView;
    WebSettings webSettings;
    SeekBar speak_volume;
    TextView txt_speak_volume;
    CheckBox repeat_is_on;  // 是否重复
    ProgressBar process_speak;  // 演讲进度
    // 次数显示
    TextView text_count_jingwen;
    TextView text_count_zhouyu;
    TextView text_count_huixiang;

    Resources res;

    String myName = "我";  // 某
    boolean no_name;

    // 闹钟
    boolean notify_is_on;
    String notify_time;
    PendingIntent clockIntent;
    // 网络状态
    CheckBox curNetworkStatus;
    NetworkChangeReceiver networkChangeReceiver;
    boolean wifi_is_connected;
    boolean cell_is_connected;
    // 消息处理
    MyHandler handler = new MyHandler(this);

    private static class MyHandler extends Handler {
        private final WeakReference<MainActivity> mActivity;

        MyHandler(MainActivity activity) {
            mActivity = new WeakReference<>(activity);  // 弱引用
        }

        @Override
        public void handleMessage(Message msg) {
            MainActivity activity = mActivity.get();
            // 消息处理
            switch (msg.what) {
                case M_PROGRESS:
                    activity.process_speak.setProgress(msg.arg1);
                    break;

                case M_NEXTCLAUSE:
                    if (activity.sutra_c.hasNext()) {
                        activity.sutra_c.next();
                    }
                    if (activity.sutra_c.finished()) {
                        activity.counter_left("0");
                        if (activity.sutra_c.getKind() == Kind.JINGWEN) {
                            activity.change_outlook(false, true, false);
                        } else if (activity.sutra_c.getKind() == Kind.ZHOUYU) {
                            activity.change_outlook(false, false, true);
                        }
                        activity.sutra_c = activity.queue.poll();
                    }
                    // 播放
                    if (activity.sutra_c != null) {
                        activity.sentence = activity.sutra_c.get_strings();
                        activity.mySpeak(Action.PLAY);
                        // 显示朗读剩余次数
                        activity.counter_left(activity.sutra_c.getCount());
                    }
                    if (activity.sutra_c == null) {
                        activity.btnStop.callOnClick();
                        if (activity.blRepeat) {
                            activity.btnPlay.callOnClick();
                        }
                    }
            }  // outer switch
        }
        //
    }

    ;

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //MultiDex.install(this);

        // 动态权限申请
        final RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions.setLogging(true);
        rxPermissions
                .request(Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_PHONE_STATE)
                .subscribe(granted -> {
                    if (granted) {
                        // All requested permissions are granted
                        // 数据
                        sharedPreferences = getApplication().getSharedPreferences("profile", MODE_PRIVATE);
                    } else {
                        Toast.makeText(MainActivity.this,
                                "Permission denied, app perhaps not work as expect",
                                Toast.LENGTH_LONG).show();
                    }
                });


        // UI element
        btnPlay = findViewById(R.id.btnPlay);
        btnPause = findViewById(R.id.btnPause);
        btnStop = findViewById(R.id.btnStop);

        webView = findViewById(R.id.jingwenHtml);
        webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        //webView.setBackgroundResource(R.drawable.bg);
        //webSettings.setDefaultFontSize(36);

        text_count_jingwen = findViewById(R.id.count_jingwen);
        text_count_zhouyu = findViewById(R.id.count_zhouyu);
        text_count_huixiang = findViewById(R.id.count_huixiang);

        process_speak = findViewById(R.id.progess_speak);

        // 伴读开启
//        speak_is_on = (CheckBox) findViewById(R.id.checkbox_speak);
//        speak_is_on.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
//            @Override
//            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//                no_speech = isChecked;
//            }
//        });

        // 循环诵读
        repeat_is_on = findViewById(R.id.checkbox_repeat);
        repeat_is_on.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                blRepeat = isChecked;
            }
        });

        txt_speak_volume = findViewById(R.id.txt_speak_volume);
        speak_volume = findViewById(R.id.speak_volume);
        speak_volume.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                // 显示
                txt_speak_volume.setText(String.format(Locale.CHINESE, "音量 %d", progress / 10));
                mTts_xunfei.set_volume(progress / 10);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                // 停止滑动
                saveSpeakVolume();
            }
        });

        //txtTitle = (TextView) findViewById(R.id.title);

        // 字符串数组
        res = getResources();

        // 语音
        mTts_xunfei = new XunfeiTTS(this);

        // 网络管理
        curNetworkStatus = findViewById(R.id.chkNetworkStatus);

        networkChangeReceiver = new NetworkChangeReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(networkChangeReceiver, intentFilter);
        networkChangeReceiver.setOnUpdateNetorkStatusListenner(new UpdateNetworkStatusListenner() {
            @Override
            public void updateNetworkStatus(int status) {

                // wifi
                wifi_is_connected = status == NetworkUtil.TYPE_WIFI;
                // 数据链接
                cell_is_connected = status == NetworkUtil.TYPE_MOBILE;
                check_network();
                curNetworkStatus.setChecked(wifi_is_connected | cell_is_connected);

                // 停止讯飞
                if (!network_is_ready) {
                    if (MainActivity.this.status == Status.PLAYING) {
                        MainActivity.this.notify("网络不可用");
                        btnStop.callOnClick();
                    }
                }
            }
        });

        // 读取档案
        readProfile();
        // 闹钟
        ClockAlarm();

        // 按钮显示： 停止
        reset();
        state_button_update(0, 0, 1);
        // 恢复显示开经偈
        //webView.loadUrl("file:///android_assets/bg.html");
        display_cover();

        // 阶段状态
        drawable_play = ContextCompat.getDrawable(getApplicationContext(), R.drawable.play);
        drawable_play.setBounds(0, 0, Objects.requireNonNull(drawable_play).getMinimumWidth(), drawable_play.getMinimumHeight());
//        drawable_play_off = ContextCompat.getDrawable(getApplicationContext(), R.drawable.play_off);
//        drawable_play_off.setBounds(0, 0, drawable_play_off.getMinimumWidth(), drawable_play_off.getMinimumHeight());

        //
    }

    // Button: 播放
    public void btnPlayClicked(View v) {
        check_network();
        if (!network_is_ready) {
            notify("网络不可用，或请关闭\"只在WiFi下使用\"");
            return;
        }

        if (status == Status.STOPPED) {
            reset();
            status = Status.PLAYING;

            // 初始化语音引擎
            // 讯飞
            mTts_xunfei.initialTts();

            // 读取数据，设置发音人            //
            readProfile();
            mTts_xunfei.set_speaker(speaker_is_male);
            mTts_xunfei.set_volume(speak_volume.getProgress() / 10);

            // 字符串初始化
            if (queue == null) {
                queue = new LinkedList<>();
            }
            queue.clear();
            Sutra sutra;
            if (type == Type.LIAOZHI) {
                // 疗痔病经
                // 经文
                sutra = new Sutra(R.string.jingwen, R.string.zhuyin, TOTAL_JINGWEN, Kind.JINGWEN, res);
                queue.add(sutra);
                // test
                //sutra.makeHTML();
                // 咒
                sutra = new Sutra(R.string.zhou, R.string.zhuyin_zhou, TOTAL_ZHOU, Kind.ZHOUYU, res);
                queue.add(sutra);
                //回向
                sutra = new Sutra(R.string.huixiang, zhuyin_huixinag, TOTAL_HUIXIANG, Kind.HUIXIANG, res);
                queue.add(sutra);

                text_count_jingwen.setText(String.format("经文：%s", TOTAL_JINGWEN));
                text_count_zhouyu.setText(String.format("咒语：%s", TOTAL_ZHOU));
                text_count_huixiang.setText(String.format("回向：%s", TOTAL_HUIXIANG));
            }
            // 没有名字不诵读
            if (type == Type.ZHOUCHI) {
                sutra = new Sutra(R.string.zhouchi, R.string.zhuyin_zhouchi, 108, Kind.JINGWEN, res);
                if (!myName.isEmpty()) {
                    sutra.replace(myName);
                }
                queue.add(sutra);
                // test
                // sutra.makeHTML();
                text_count_jingwen.setText(String.format("经文：%s", 108));
                text_count_zhouyu.setText(String.format("咒语：%s", 0));
                text_count_huixiang.setText(String.format("回向：%s", 0));
            }
            // 药师佛经
            if (type == Type.YAOSHIFO) {
                sutra = new Sutra(R.string.jingwen_yaoshifo, R.string.zhuyin_jingwen_yaoshifo,
                        TOTAL_JINGWEN, Kind.JINGWEN, res);
                queue.add(sutra);
                sutra.makeHTML();
                /*sutra = new Sutra(R.string.xinzhou_yaoshifo, R.string.zhuyin_xinzhou_yaoshifo,
                        TOTAL_ZHOU, Kind.ZHOUYU, res);
                queue.add(sutra);*/

                text_count_jingwen.setText(String.format("经文：%s", TOTAL_JINGWEN));
                text_count_zhouyu.setText(String.format("咒语：%s", 0));
                text_count_huixiang.setText(String.format("回向：%s", 0));
            }
            // 心经
            if (type == Type.XINJING) {
                sutra = new Sutra(R.string.jingwen_xinjing, R.string.zhuyin_xinjing,
                        TOTAL_JINGWEN, Kind.JINGWEN, res);
                queue.add(sutra);
                //sutra.makeHTML();

                text_count_jingwen.setText(String.format("经文：%s", TOTAL_JINGWEN));
                text_count_zhouyu.setText(String.format("咒语：%s", 0));
                text_count_huixiang.setText(String.format("回向：%s", 0));
            }

            // 获取读字符串
            sutra_c = queue.poll();
            if (sutra_c != null) {
                sentence = sutra_c.get_strings();
                mySpeak(Action.PLAY);
            }

        } else if (status == Status.PAUSED) {
            status = Status.PLAYING;
            mySpeak(Action.RESUME);
        }
        // 按钮状态图
        state_button_update(1, 0, 0);
        change_outlook(true, false, false);
        //
    }

    // Button: 暂停
    public void btnPauseClicked(View v) {
        if (status == Status.PLAYING) {
            mySpeak(Action.PAUSE);
            status = Status.PAUSED;
            // 按钮状态图
            state_button_update(0, 1, 0);
        }

    }

    // Button: 停止
    public void btnStopClicked(View v) {
/*        if (mTts.isSpeaking()) {
            mTts.stopSpeaking();
            status = Status.STOPPED;
        }*/
        if (status == Status.STOPPED) return;
        mySpeak(Action.STOP);
        status = Status.STOPPED;
        // 显示开经偈
        //webView.loadUrl("file:///android_assets/bg.html");
        display_cover();
        // 按钮状态图
        state_button_update(0, 0, 1);
        // icon play

        change_outlook(false, false, false);
    }

    @Override
    protected void onPause() {
        btnPause.callOnClick();
        super.onPause();
    }

    @Override
    protected void onStop() {
        if (status == Status.PLAYING)
            btnPause.callOnClick();
        super.onStop();
    }

    // save

    @Override
    protected void onDestroy() {
        unregisterReceiver(networkChangeReceiver);
        btnStop.callOnClick();
        super.onDestroy();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    // resume
    @Override
    protected void onResume() {
        if (status == Status.PAUSED)
            btnPlay.callOnClick(); // add 2017.09.05
        super.onResume();
        //
    }

    // 菜单
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Intent intent;
        switch (item.getItemId()) {
            case R.id.menu_setting:
                intent = new Intent(MainActivity.this, SettingActivity.class);
                startActivityForResult(intent, CODE_SETTING);
                break;

            case R.id.menu_about:
                intent = new Intent(MainActivity.this, AboutActivity.class);
                startActivity(intent);
                break;

            case R.id.menu_support:
                intent = new Intent(MainActivity.this, SupportActivity.class);
                startActivity(intent);
                break;
            case R.id.menu_liaozhibingjing:
                this.setTitle("佛说疗痔病经");
                item.setChecked(true);
                type = Type.LIAOZHI;

                break;
            case R.id.menu_zhouchijing:
                this.setTitle("佛说咒齿经");
                item.setChecked(true);
                type = Type.ZHOUCHI;
                // 输入名字替代 “某”
                if (sharedPreferences != null && Objects.requireNonNull(sharedPreferences.getString("myname", "")).isEmpty()) {
                    final EditText et = new EditText(this);
                    et.setInputType(InputType.TYPE_CLASS_TEXT);
                    et.setMaxLines(1);
                    et.setMaxEms(12);
                    AlertDialog.Builder builder = new AlertDialog.Builder(this);
                    builder.setTitle("请输入牙疼者的名字").setView(et)
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    String name = et.getText().toString();
                                    if (name.isEmpty()) {
                                        Snackbar.make(btnPlay, "若不填写名字，则继续使用原字", Snackbar.LENGTH_LONG).show();
                                    } else {
                                        String regEx = "^[\\u4E00-\\u9FA5\\uF900-\\uFA2D]+$";
                                        Pattern pattern = Pattern.compile(regEx);
                                        Matcher matcher = pattern.matcher(name);
                                        if (matcher.matches()) {
                                            no_name = false;
                                            myName = name;
                                            // 保存
                                            save("myname", name);
                                        } else {
                                            Snackbar.make(btnPlay, "请输入中文名字", Snackbar.LENGTH_LONG).show();
                                        }
                                    }
                                }
                            });
                    builder.show();
                }
                break;
            case R.id.menu_yaoshi:
                this.setTitle("药师佛经");
                item.setChecked(true);
                type = Type.YAOSHIFO;

                break;

            case R.id.menu_xinjing:
                this.setTitle("心经");
                item.setChecked(true);
                type = Type.XINJING;

                break;
            case R.id.menu_sutra_zhouchi:
                intent = new Intent(MainActivity.this, SutraActivity.class);
                intent.putExtra("title", "佛说咒齿经");
                intent.putExtra("html", "zhouchi.html");
                startActivity(intent);
                break;

            case R.id.menu_sutra_liaozhi:
                intent = new Intent(MainActivity.this, SutraActivity.class);
                intent.putExtra("title", "佛说疗痔病经");
                intent.putExtra("html", "liaozhibingjing.html");
                startActivity(intent);
                break;

            case R.id.menu_sutra_yaoshi:
                intent = new Intent(MainActivity.this, SutraActivity.class);
                intent.putExtra("title", "药师佛经");
                intent.putExtra("html", "yaoshifo.html");
                startActivity(intent);
                break;
            case R.id.menu_sutra_xinjing:
                intent = new Intent(MainActivity.this, SutraActivity.class);
                intent.putExtra("title", "心经");
                intent.putExtra("html", "xinjing.html");
                startActivity(intent);
                break;
            case R.id.menu_privacy:
                intent = new Intent(MainActivity.this, SutraActivity.class);
                intent.putExtra("title", "隐私政策");
                intent.putExtra("html", "privacy.html");
                startActivity(intent);
                break;
/*            case R.id.menu_sutra_story:
                intent = new Intent(MainActivity.this, SutraActivity.class);
                intent.putExtra("title", "佛经故事");
                intent.putExtra("html", "zhouchi.html");
                startActivity(intent);
                break;*/
        }

        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CODE_SETTING) {
            if (resultCode == RESULT_OK) {
                // 读取档案
                readProfile();
                // 闹钟
                ClockAlarm();
            } // if ok
        }  // switch
    }

    // *数据：速度
    // 保存
    private void saveSpeakVolume() {
        if (sharedPreferences == null) return;
        SharedPreferences.Editor editor = this.sharedPreferences.edit();
        editor.putInt("speak_volume", speak_volume.getProgress() / 10);  // 取显示的音量
        editor.apply();
    }

    // 读取配置文件
    private void readProfile() {

        if (sharedPreferences == null) {
            speak_volume.setProgress(50);
            speaker_is_male = true;

            notify_is_on = false;
            notify_time = "20:00";

            wifi_is_only = true;

            // 修持次数
            TOTAL_JINGWEN = 1;
            text_count_jingwen.setText(String.format(Locale.CHINESE, "经文 %d", TOTAL_JINGWEN));

            TOTAL_ZHOU = 3;
            text_count_zhouyu.setText(String.format(Locale.CHINESE, "咒语 %d", TOTAL_ZHOU));

            // 某
            myName = "某";
        } else {

            int v = this.sharedPreferences.getInt("speak_volume", 5);
            speak_volume.setProgress(v * 10);
            speaker_is_male = sharedPreferences.getBoolean("is_male", true);

            notify_is_on = sharedPreferences.getBoolean("notify_is_on", true);
            notify_time = sharedPreferences.getString("notify_time", "20:00");

            wifi_is_only = sharedPreferences.getBoolean("wifi_is_only", true);

            // 修持次数
            TOTAL_JINGWEN = Integer.parseInt(Objects.requireNonNull(sharedPreferences.getString("set_count_jingwen", "1")));
            text_count_jingwen.setText(String.format(Locale.CHINESE, "经文 %d", TOTAL_JINGWEN));

            TOTAL_ZHOU = Integer.parseInt(Objects.requireNonNull(sharedPreferences.getString("set_count_zhouyu", "3")));
            text_count_zhouyu.setText(String.format(Locale.CHINESE, "咒语 %d", TOTAL_ZHOU));

            // 某
            myName = sharedPreferences.getString("myname", "");
        }
    }

    // 检查网络
    private boolean checkNetwork() {

        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

        try {
            NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
            boolean isWiFi = activeNetwork.getType() == ConnectivityManager.TYPE_WIFI;

            return isWiFi || activeNetwork.isConnected();
        } catch (NullPointerException e) {
            return false;
        }
    }

    // speak 动作
    private void mySpeak(Action action) {

        switch (action) {
            case PLAY:
                if (sentence.length == 2) {
                    mTts_xunfei.speak(sentence[0]);
                    webView.clearFormData();
                    webView.loadData(sentence[1], "text/html;charset=utf-8", "utf-8");
                }
                break;

            case PAUSE:
                mTts_xunfei.pause();
                break;

            case RESUME:
                mTts_xunfei.resume();
                break;

            case STOP:
                mTts_xunfei.stop();
                break;
        }
//
    }

    // 按钮显示刷新
    private void state_button_update(int play, int pause, int stop) {

        if (play == 1)
            btnPlay.setTextColor(Color.GREEN);
        else
            btnPlay.setTextColor(Color.RED);

        if (pause == 1)
            btnPause.setTextColor(Color.GREEN);
        else
            btnPause.setTextColor(Color.RED);

        if (stop == 1)
            btnStop.setTextColor(Color.GREEN);
        else
            btnStop.setTextColor(Color.RED);
    }

    // 复位
    private void reset() {
        // debug
        //idx_line = idx_max - 1;

        count_jingwen = 0;
        count_zhouyu = 0;
        count_huixiang = 0;

        status = Status.STOPPED;

        // ui reset
        text_count_jingwen.setText(String.format(Locale.CHINESE, "经文 %d",
                TOTAL_JINGWEN));
        text_count_zhouyu.setText(String.format(Locale.CHINESE, "咒语 %d",
                TOTAL_ZHOU));
        text_count_huixiang.setText(String.format(Locale.CHINESE, "回向 %d",
                TOTAL_HUIXIANG));
    }

    /* 显示提醒 */
    public void notify(String info) {
        Toast.makeText(getApplication(), info, Toast.LENGTH_LONG).show();
    }

    /* 读取网页 */
    private void display_cover() {

        webView.loadUrl("file:///android_res/raw/bg.html");
        process_speak.setProgress(0);
    }

    /* 修改计数外观 */
    private void change_outlook(boolean jingwen, boolean zhouyu, boolean huixiang) {

        if (jingwen) {
            text_count_jingwen.setCompoundDrawables(drawable_play, null, null, null);
        } else {
            text_count_jingwen.setCompoundDrawables(null, null, null, null);
        }
        if (zhouyu) {
            text_count_zhouyu.setCompoundDrawables(drawable_play, null, null, null);
        } else {
            text_count_zhouyu.setCompoundDrawables(null, null, null, null);
        }
        if (huixiang) {
            text_count_huixiang.setCompoundDrawables(drawable_play, null, null, null);
        } else {
            text_count_huixiang.setCompoundDrawables(null, null, null, null);
        }

    }

    /* 检查网络是否可用 */
    private void check_network() {
        network_is_ready = (wifi_is_only & wifi_is_connected) | (!wifi_is_only & cell_is_connected);
    }

    /* 闹钟 */
    private void ClockAlarm() {
        // 检查闹钟
        Intent alarmIntent = new Intent(MainActivity.this, AlarmReceiver.class);
        final PendingIntent pendingIntent =
                PendingIntent.getBroadcast(MainActivity.this, 0, alarmIntent,
                        PendingIntent.FLAG_NO_CREATE);

        if (!this.notify_is_on) {
            if (pendingIntent != null) {
                pendingIntent.cancel();  // 取消闹钟
            }
        } else {
            // 设置闹钟
            String time[] = this.notify_time.split(":");
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(System.currentTimeMillis());
            calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(time[0]));
            calendar.set(Calendar.MINUTE, Integer.parseInt(time[1]));
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);

            AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
            Context context = getApplication();
            Intent intent = new Intent(context, AlarmReceiver.class);

            clockIntent = PendingIntent.getBroadcast(context, 100, intent,
                    PendingIntent.FLAG_UPDATE_CURRENT);

            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
                    AlarmManager.INTERVAL_DAY, clockIntent);
        }
        // end
    }

    // 存到share
    private void save(String key, String v) {
        SharedPreferences.Editor editor = getSharedPreferences("profile", MODE_PRIVATE).edit();
        editor.putString(key, v);
        editor.apply();
    }

    private void save(String key, int v) {
        SharedPreferences.Editor editor = getSharedPreferences("profile", MODE_PRIVATE).edit();
        editor.putFloat(key, v);
        editor.apply();
    }

    // 显示剩余次数
    private void counter_left(String count) {
        switch (sutra_c.getKind()) {
            case JINGWEN:
                text_count_jingwen.setText(String.format("经文：%s", count));
                break;
            case ZHOUYU:
                text_count_zhouyu.setText(String.format("咒语：%s", count));
                break;
            case HUIXIANG:
                text_count_huixiang.setText(String.format("回向：%s", count));
                break;
        }
    }

    /* google index code */

    //
}